package com.kobeliu.service.impl;

import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.pojo.PayResult;
import com.kobeliu.pojo.PreOrderResult;
import com.kobeliu.resource.WxPayResource;
import com.kobeliu.service.WxOrderService;
import com.kobeliu.utils.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletInputStream;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

@Service
public class WxOrderServiceImpl extends BaseInfoProperties implements WxOrderService {

    @Autowired
    private WxPayResource wxPayResource;


    @Override
    public PreOrderResult placeOrder(String body, String outTradeNo, String totalFee) {

        PreOrderResult o = new PreOrderResult();
        //生成随机字符串
        String nonce_str = UUID.randomUUID().toString().trim().replaceAll("-","0");

        o.setAppId(wxPayResource.getAppId());
        o.setBody(body);
        o.setMch_id(wxPayResource.getMerchantId());
        o.setNotify_url(wxPayResource.getNotifyUrl());
        o.setOut_trade_no(outTradeNo);

        //判断有没有输入订单总金额，没有就默认输入一分钱
        if(totalFee != null && !totalFee.equals("")){
            o.setTotal_fee(Integer.valueOf(totalFee));
        }else{
            o.setTotal_fee(1);
        }
        o.setNonce_str(nonce_str);
        o.setTrade_type(wxPayResource.getTradeType());
        o.setSpbill_create_ip(wxPayResource.getSpbillCreateIp());

        TreeMap<String, String> p = new TreeMap<>();
        p.put("appid",wxPayResource.getAppId());

        p.put("mch_id",wxPayResource.getMerchantId());
        p.put("body",body);
        p.put("nonce_str",nonce_str);
        p.put("out_trade_no",outTradeNo);
        p.put("total_fee",totalFee);
        p.put("spbill_create_ip",wxPayResource.getSpbillCreateIp());
        p.put("notify_url",wxPayResource.getNotifyUrl());
        p.put("trade_type",wxPayResource.getTradeType());

        //获得签名
        String sign = SignUtil.createSign(p,wxPayResource.getMerchantId());

        o.setSign(sign);

        //object 转xml
//        String xml = XmlUtil.
//
//        restTemplate发送请求
//        返回xml格式
        //xml 转obj -> preOrderResult

//        返回这个返回的preOrderResult
        return o;
    }

    @Override
    public PayResult getWxPayResult(ServletInputStream inputStream) {

        String s = inputStream.toString();
        PayResult result = new PayResult();
        return result;
    }
}
